<!DOCTYPE html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加订单</title>
    <link rel="stylesheet" href="<%=basePath %>web/themes/icon.css">
    <link rel="stylesheet" href="<%=basePath %>web/themes/default/easyui.css">
    <link rel="stylesheet" href="<%=basePath %>web/css/wu.css">
	<script src="<%=basePath %>web/js/jquery.min.js"></script>
    <script src="<%=basePath %>web/js/jquery.easyui.min.js"></script>
    <script src="<%=basePath %>web/js/easyui-lang-zh_CN.js"></script>
    <script>
        function loadSupplier() {
            $("#list").dialog({
                title: '供应商列表,双击可选中',
                width: 905,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           })
        }
          
        function closeSupplier(){
        	$("#partList").dialog("destroy");
        	$("#part_List_parent").html("<div id='partList'  style='display: none' data-options='onClose:function(){closeSupplier()}'>"+
        	"<iframe src='<%=basePath%>web/goods/purchaseOrderBill_Part.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        function closeSupplier1(){
        	$("#partList1").dialog("destroy");
        	$("#part_List_parent1").html("<div id='partList1'  style='display: none' data-options='onClose:function(){closeSupplier1()}'>"+
        	"<iframe src='<%=basePath%>web/goods/purchaseOrderBill_inquirybill.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        function loadPart() {
        var na=$("#supplierName").textbox('getText')
        	if(!na){
        	$.messager.alert('我的消息','供应商名称不能为空!','warning');
        	 return;
        	}
            $("#partList").dialog({
                title: '选择配件',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           })
        } 
        function loadInquiry() {
        	if(!$("#supplierName").textbox('getText')){
        	$.messager.alert('我的消息','供应商名称不能为空!','warning');
        	 return;
        	}
            $("#partList1").dialog({
                title: '选择询价单',
                width: 1000,
                height: 400,
                closed: false,
                cache: false,
                modal: true,
           })
        } 
          function closePart() {
            $("#partList").dialog("close");
        }
          function closePart1() {
            $("#partList1").dialog("close");
        }
         function closeDg(name) {
            $("#supplierName").val(name);
            $("#list").dialog("close");
        }
         //用于将子页面的数据绑定到相关元素上
        function bindValue(data){
        	var name=data[0];
        	var linkman=data[1];
        	var phone=data[2];
        	var fax=data[3];
        	$('#supplierName').textbox('setValue',name);	
        	$('#contacter').textbox('setValue',linkman);	
        	$('#phone').textbox('setValue',phone);	
        	$('#fax').textbox('setValue',fax);	
        }
   
        function closeSon(){
        	 $("#list").dialog("destroy");
        	 $("#absolute").html("<div id='list'  style='display: none' data-options='onClose:function(){closeSon()}'>"+
        	"<iframe src='<%=basePath%>web/goods/purchaseOrderBill_supplier.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>"+
        	"</div>"); 
        }
        function reloads(){
        	location.reload();
        }
	    
         $(function(){
           var path=$("#path").val();
           	$("#generatingParts").datagrid({
                checkOnSelect:true,
                rownumbers:true,
                columns:[[
                    {field:'code',title:'配件编号',width:130},
                    {field:'partName',title:'配件名称',width:167},
                    {field:'billCode',title:'询价编号',width:130},
                    {field:'partBrand',title:'配件品牌',width:100},
                    {field:'partNo',title:'配件型号',width:100},
                    {field:'amount',title:'数量',width:98,
                    	 formatter:function(value,row,index){
                            return '<input type="number" name="amount" onchange="change_amount_sellPrice('+index+',this)"  value="'+value+'" style="width:50px;"/>';
                        }
                    },
                    {field:'sellPrice',title:'单价',width:90, 
                        formatter:function(value,row,index){
                        if(row.sellPrice==null){
                    		return null;
                    	}
                            return '<input type="number" name="sellPrice" onchange="change_amount_sellPrice('+index+',this)"  value="'+value+'" style="width:50px;"/>';
                        }
                    },
                    {field:'price',title:'总金额',width:90,
                         formatter:function(value,row,index){
                            return "￥"+row.price;
                        }
                    },
	                {field:'memo',title:'备注',width:100,
	                    formatter:function(value,row,index){
		                     if(row.sellPrice==null){
		                    	return null;
		                      }
	                         return '<input class="partmemo" type="text" value="" style="width:80px;"/>';
	                      }
	                 }, 
                    {field:'opt',title:'操作',width:100,formatter:function (value,row,index) {
                        if(row.sellPrice==null){
                    		return null;
                    	}
                            var context="<a href=\"javascript:del('"+index+"')\" style='color:blue;text-decoration:underline;'>删除</a>&nbsp;&nbsp;" 
                            return context;
                        }}

                ]],
                toolbar:'#wu_toolbar'
            
            })
            
	          $.ajax({
				type:"post",//请求类型
				url:path+"PurchaseOrderBill/makenewcode?prefix=CG", 
				dataType:"json",//ajax接口（请求url）返回的数据类型
				success:function(data){//data：返回数据（json对象）
				   $("#code").textbox({'value':data.result});
				}
		    });
			    var newdate=new Date();
			    $("#addDate").datetimebox("setValue",myformatter(newdate));
			    
			   $("#save").click(function(){
			  	 $.messager.confirm('添加消息','您确认添加吗?',function(r){    
					  if (r){    
					          var ms=[];
			   		var oldRow=$('#generatingParts').datagrid('getRows');
			    	var f=$("#form").serialize();
			    	var de=$("#deliveryTime").textbox('getText');
			    	var data =JSON.stringify($('#generatingParts').datagrid('getData').rows);
			    	if(de==null || de==''){
			    			$.messager.alert('我的消息','请填写交货时间!','warning');
			    	}else{
				    	if(oldRow==null||oldRow==''){
			        		$.messager.alert('我的消息','没有添加配件信息!','warning');
				    	}else{
				    	var money=parseFloat(oldRow[oldRow.length-1]['price']);
				    	$(".partmemo").each(function(){
        					ms.push($(this).val());
        				});
        				var memo=JSON.stringify(ms)
							 $.ajax({
								type:"get",//请求类型
								url:path+"PurchaseOrderBill/addBill_Detail?"+f, 
								dataType:"json",//ajax接口（请求url）返回的数据类型
								data:{'data':data,'money':money,'mm':memo},
								success:function(data){//data：返回数据（json对象）
								   if(data=="y"){
								    	alert("添加成功!");
								      parent.addTabs('采购订单管理',path+'web/goods/purchaseOrderBill.jsp');
        						      parent.closeTabs('添加订单');
								   }else{
								   	   alert("添加失败!");
								   }
								}
					        });
					    }
			    	}     
					    }   
					});
			   })
           })
        //增加
 //用于将子页面的数据绑定到相关元素上
         function addpart1(row){
            var flag=true;
            var x=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                   if(oldRow[j]['code']==row[i]['code']&&oldRow[j]['billCode']==row[i]['billCode']){
         		       $.messager.alert('我的消息','不能重复添加询价配件','warning');
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==true){
                 }else{
                 	break;
                 }
                }else{
                	addToPage1(row[i]);
                	x=false;
                }
             }
             if(flag==true){
             	if(x==true){
                 	for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage1(row[i]);
					}
                }else{
                 	for(var i=1;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage1(row[i]);
					}	
                }
              }
              closePart1();
         }
 //用于将子页面的数据绑定到相关元素上
         function addpart(row){
            var flag=true;
            var x=true;
            var oldRow=$('#generatingParts').datagrid('getRows');
            for(var i=0;i<row.length;i++){
               if(oldRow!=null&&oldRow!=''){
                 for(var j=0;j<oldRow.length;j++){
                   if(oldRow[j]['code']==row[i]['code']){
         		       $.messager.alert('我的消息','不能重复添加配件','warning');
         		       flag=false;
         		       break;
         		   }
                 } 
                 if(flag==true){
                 }else{
                 	break;
                 }
                }else{
                	addToPage(row[i]);
                	x=false;
                }
             }
             if(flag==true){
             	if(x==true){
                 	for(var i=0;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage(row[i]);
					}
                }else{
                 	for(var i=1;i<row.length;i++){
			         $('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
                 	 addToPage(row[i]);
					}	
                }
              }
              closePart();
         }
        //
        function addToPage(row){
           $('#generatingParts').datagrid('appendRow',{
           		
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: 1,
				sellPrice: row.sellPrice,
				price: row.sellPrice,
				memo: row.memo,
				opt: row.opt
		   });
		   
		   $("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
          })
        }
        function addToPage1(row){
           $('#generatingParts').datagrid('appendRow',{
           		billCode:row.billCode,
				code: row.code,
				partName: row.partName,
				partBrand: row.partBrand,
				partNo: row.partNo,
				amount: row.amount,
				sellPrice: row.sellPrice,
				price: row.sellPrice*row.amount,
				memo: row.memo,
				opt: row.opt
		   });
		   
		   $("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
          })
        }
          function total(col){
        	var rows=$("#generatingParts").datagrid('getRows');
        	var total=0;
        	for(var i=0;i<rows.length;i++){
        		total+=parseFloat(rows[i][col]);
        	}
        	return total;
          }
        function myformatter(date){
          var y=date.getFullYear();
          var m=date.getMonth()+1;
          var d=date.getDate();
          var hh=date.getHours();       //获取当前小时数(0-23)
	      var mm=date.getMinutes();     //获取当前分钟数(0-59)
          var dd=date.getSeconds();     //获取当前秒数(0-59)
          return y+"-"+(m<10?('0'+m):m)+"-"+(d<10?('0'+d):d)+" "+(hh<10?('0'+hh):hh)+":"+(mm<10?('0'+mm):mm)+":"+(dd<10?('0'+dd):dd);
        }
        function change_amount_sellPrice(input_index,input){
        
         	var amount=$(input).parent().parent().parent().find('[name="amount"]').val();
         	var avg=$(input).parent().parent().parent().find('[name="sellPrice"]').val();
         	var price=parseFloat(amount)*parseFloat(avg);
         	$('#generatingParts').datagrid('updateRow',{
				index: input_index,
				row: {
					amount: amount,
					sellPrice:avg,
					price: price
				}
			});
			var oldRow=$('#generatingParts').datagrid('getRows');
			$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
			$("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
         }
            function del(index){
         	//删除当前行
         	$('#generatingParts').datagrid('deleteRow',index);
         	//拿到之前的数据并重新封装，刷新index
         	var oldData=$('#generatingParts').datagrid('getData');
         	$('#generatingParts').datagrid('loadData',oldData);
         	//更新最后一行
         	var oldRow=$('#generatingParts').datagrid('getRows');
         	$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
			$("#generatingParts").datagrid('appendRow',{
                	  'partBrand':"合计",
                	  'amount':total('amount'),
                	  'price':total('price')
           	});
          	if(oldRow.length==1){
          		$('#generatingParts').datagrid('deleteRow',oldRow.length-1); 
          	}
         }
          function loadClose(){
        	parent.closeTabs('添加订单')
        }
    </script>
    <style>
        body {
            font-size:12px;
            padding:10px
        }
        .l-table-edit {
            border:#84a0c4 1px solid
        }
        .l-table-edit-td {
            padding:4px;
            font-size:12px;
        }
        
    </style>


</head>
<body>
<form name="form"  id="form" action="" method="post">
    <table cellpadding="0" cellspacing="0" class="l-table-edit" style="width:100%;" border="1">
        <tr >
            <td width="17%"  align="right" class="l-table-edit-td">订单编号：</td>
            <td width="27%" align="left" class="l-table-edit-td">
           	    <input  type="text" class="easyui-textbox" id="code" value="" name="code" maxlength="100" ltype="text" style="height:20px" readonly="readonly" />
            </td>
            <td width="13%"  align="right" class="l-table-edit-td">订单日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input  type="text" name="orderTime" id="addDate" value="" maxlength="30" class="easyui-datetimebox" style="height:20px" />
            </td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">
                <a href="javascript:loadSupplier()" style="color: blue;text-decoration: underline;">供应商名：</a>
            </td>
            <td align="left" class="l-table-edit-td" width="27%">
      
                <input type="text" id="supplierName" name="supplierName" value="" class="easyui-textbox"  maxlength="100" ltype="text"  style="height:20px" readonly="readonly"/>
            </td>
            <td width="13%" align="right" class="l-table-edit-td">联系人员：</td>
            <td align="left" class="l-table-edit-td" width="43%">
                <input name="linkman" type="text" id="contacter" value="" class="easyui-textbox" maxlength="30" ltype="text" style="height:20px"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">电话：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" id="phone"class="easyui-textbox" value="" name="phone" maxlength="50" ltype="text" style="height:20px"/></td>
            <td width="13%" align="right" class="l-table-edit-td">传真：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input type="text" name="fax" id="fax" class="easyui-textbox" value="" maxlength="50"  ltype="text" style="height:20px"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">运输方式：</td>
            <td width="27%" align="left" class="l-table-edit-td">
             <select name="shippingMode" id="shippingMode" class="easyui-combobox" style="width:100px;height:20px" panelHeight="150px">
             	<c:if test="${list!=null }">
             		<c:if test="${list.shippingMode==1 }">
             		  	<option value="1" selected="selected">圆通快递</option> 
             		  	<option value="2">中通快递</option> 
             		</c:if>
             		<c:if test="${list.shippingMode==2 }">
             			<option value="1">圆通快递</option> 
             		  	<option value="2" selected="selected">中通快递</option> 
             		</c:if>
             	</c:if>
             	<c:if test="${list==null }">
                 <option value="1">圆通快递</option> 
                 <option value="2">中通快递</option> 
             	</c:if>
             </select>
            </td>
            <td width="13%" align="right" class="l-table-edit-td">业务人员：</td>
            <td width="43%"align="left" class="l-table-edit-td"><input type="text" name="admin" class="easyui-textbox"  id="admin" value="admin" maxlength="50"  ltype="text" style="height:20px" readonly="readonly"/></td>
        </tr>
        <tr>
            <td width="17%" align="right" class="l-table-edit-td">备注：</td>
            <td width="27%" align="left" class="l-table-edit-td"><input  type="text" class="easyui-textbox" name="memo" id="type" value="${list.memo }" maxlength="50" ltype="text" style="height:20px"/></td>
            <td width="13%" align="right" class="l-table-edit-td">交货日期：</td>
            <td width="43%" align="left" class="l-table-edit-td"><input type="text"  class="easyui-datetimebox" id="deliveryTime" name="deliveryTime" value="<fmt:formatDate value="${list.deliveryTime}" pattern="yyyy-MM-dd"/>" maxlength="50"  ltype="text" style="height:20px"/></td>
        </tr>
    </table>
</form>
<br>
<input type="hidden" id="path" value="<%=basePath%>"/>
<input  type="button" value="新   增" style="width:60px" onclick="reloads()">
<a href="javascript:loadInquiry()"><input  type="button" value="选询价单" style="width:60px"></a>
<a href="javascript:loadPart()"><input  type="button" value="添加配件" style="width:60px"></a>
<input  type="button" value="保存" style="width:60px" id="save">
<input  type="button" value="审核" style="width:60px">
<a href="javascript:loadClose()"><input  type="button" value="关闭" style="width:60px"></a>
<br/><br/>
<div id="generatingParts" class="easyui-datagrid">

</div>
<div id="absolute">
	<div id="list"  style="display: none" data-options="onClose:function(){closeSon()}">
    	<iframe src='<%=basePath %>web/goods/purchaseOrderBill_supplier.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
	</div>
</div>
<div id="part_List_parent">
	<div id="partList"  style="display: none" data-options='onClose:function(){closeSupplier()}'>
	 <iframe src='<%=basePath %>web/goods/purchaseOrderBill_Part.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
	</div>
</div>
<div id="part_List_parent1">
	<div id="partList1"  style="display: none" data-options='onClose:function(){closeSupplier1()}'>
		 <iframe src='<%=basePath %>web/goods/purchaseOrderBill_inquirybill.jsp' frameborder='0'style='width: 100%;height: 100%'></iframe>
	</div>
</div>
</body>
</html>